package com.hongliang.netty02.decoder;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Random;

/**
 * 预设长度： 在发送消息前，先约定用定长字节表示接下来数据的长度
 *
 * @author Hongliang Zhu
 * @create 2022-11-08 22:15
 */
@Slf4j
public class PreSetLengthClient {

    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class);
            ChannelFuture channelFuture = bootstrap.group(group)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            log.debug("connetted...");
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    log.debug("sending message...");
                                    ByteBuf buffer = ctx.alloc().buffer();

                                    Random r = new Random();
                                    char c = 'a';

                                    for (int i = 0; i < 10; i++) {
                                        byte length = (byte) (r.nextInt(16) + 1);
                                        // 先写长度
                                        buffer.writeByte(length);
                                        // 再写消息
                                        for (int j = 0; j < length; j++) {
                                            buffer.writeByte((byte) c);
                                        }
                                        c++;
                                    }

                                    // 发送
                                    ctx.writeAndFlush(buffer);
                                }
                            });


                        }
                    }).connect(new InetSocketAddress("localhost", 8080)).sync();

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException ex) {
            log.error("client error", ex);

        } finally {
            group.shutdownGracefully();
        }

    }
}
